﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SnippetBox.Core.Common.Extensions;
using SnippetBox.Core.Data.Context;
using SnippetBox.Core.Data.Models;
using SnippetBox.Core.Data.Service;

namespace SnippetBox.Web.Controllers
{
    public class InstallController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }        
        
        [HttpPost, ActionName("Index")]
        public ActionResult IndexPost()
        {
            var context = new DatabaseContext();
            var script = ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();
            var response = context.Database.ExecuteSqlCommand(script);
            
            GenerateSampleData(context);
            
            context.SaveChanges();

            return RedirectToAction("Index", "Snippets");
        }

        public void GenerateSampleData(DatabaseContext context) {
            var user = new User("admin", "5447aed2fdae62d1a4ce8b832beaf865");
            user.Role = Role.SuperAdmin;

            var category1 = new Category("Sample");
            var category2 = new Category("JavaScript");
            var category3 = new Category("HTML");
            var category4 = new Category("CSS");

            context.Categories.Add(category1);
            context.Categories.Add(category2);
            context.Categories.Add(category3);
            context.Categories.Add(category4);

            var snippet1 = new Snippet("Welcome to Snippet Box", "This snippet post is a sample. Login to your new Snippet Box with admin/admin.", category1, user);
            context.Users.Add(user);
            context.Snippets.Add(snippet1);

        }

    }
}
